import json

from django.contrib.auth import login, logout, authenticate
from django.http import JsonResponse
from django.views import View


class UsersLogin(View):
    def post(self, request):
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')
        if not all([mobile, password]):
            return JsonResponse({
                'errno': '4102',
                'errmsg': 'Required parameter missing'
            }, status=402)
        user = authenticate(password=password, username=mobile)

        if not user:
            return JsonResponse({
                "errno": '0',
                "errmsg": "Wrong username or password"
            }, status=402)
        login(request, user)

        return JsonResponse({
            "errno": '0',
            "errmsg": "Login successful"
        })

    def get(self, request):

        """username右上角展示"""
        if request.user.is_authenticated:
            data = {
                'name': request.user.username,
                'user_id': request.user.id
            }
            return JsonResponse({
                "errno": '0',
                "errmsg": 'Logged in',
                'data': data
            })
        else:
            return JsonResponse({
                "errno": '4101',
                "errmsg": 'Not logged in'
            })

    def delete(self, request):
        logout(request)
        return JsonResponse({
            "errno": '0',
            "errmsg": 'Sign out'
        }, status=204)